package com.workcell.workdata.im.component.validator;

import com.workcell.workdata.im.annotation.validator.MomentImageFormat;
import com.workcell.workdata.im.entity.Moment;
import com.workcell.workdata.im.model.message.CloudImage;
import com.workcell.workdata.im.model.request.MomentRequest;
import com.workcell.workdata.im.util.JSON;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class MomentImageValidator implements ConstraintValidator<MomentImageFormat, MomentRequest>, Predicate<CloudImage> {

    @Override
    public boolean isValid(MomentRequest request, ConstraintValidatorContext context) {
        if (request.getType() != Moment.FORMAT_IMAGE && request.getType() != Moment.FORMAT_MULTI_IMAGE){
            return true;
        }

        List<CloudImage> imageList = new ArrayList<>();

        if (request.getType() == Moment.FORMAT_IMAGE){
            CollectionUtils.addIgnoreNull(imageList,JSON.parseNullable(request.getContent(),CloudImage.class));
        }
        if (request.getType() == Moment.FORMAT_MULTI_IMAGE){
            imageList.addAll(JSON.parseListNullable(request.getContent(),CloudImage.class));
        }

        return !imageList.isEmpty() && imageList.stream().noneMatch(this);
    }

    /**
     * 匹配不正确的数据格式
     * @param image the input argument
     * @return
     */
    @Override
    public boolean test(CloudImage image) {
        return StringUtils.isAnyEmpty(image.getImage(),image.getThumb(),image.getBucket())
                || image.getTh() == 0
                || image.getOh() == 0
                || image.getTw() == 0
                || image.getOw() == 0;
    }
}
